package com.hctforgreen.greenservice;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshWebView;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.DbKeywordController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BaseEntity;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.BookZipTxtEntity;
import com.hctforgreen.greenservice.model.BookZipTxtEntity.EntryEntity;
import com.hctforgreen.greenservice.model.EntryCatalogEntity;
import com.hctforgreen.greenservice.model.KeywordListEntity;
import com.hctforgreen.greenservice.model.KeywordListEntity.KeywordEntity;
import com.hctforgreen.greenservice.service.HctApplication;
import com.hctforgreen.greenservice.ui.adapter.SearchHistoryListAdapter;
import com.hctforgreen.greenservice.ui.widget.ScrollWebView;
import com.hctforgreen.greenservice.ui.widget.ScrollWebView.OnScrollChangedCallback;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.hctforgreen.greenservice.utils.UnZipUtil;

/**
 * 下拉 上拉webview 翻页查看 说明书详情页(若当一条搜索失败，则当多条搜索)
 * 
 * @author Tallen Zhai
 * 
 */
public class EntryDetailV3Activity extends ParentActivity {
	private boolean fromY;

	private int currentIndex;
	private LinkedHashMap<String, String> bookIds = new LinkedHashMap<String, String>();// key:id
	// value:bookId

	private List<String> titleNames = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_entry_detail_v3);
		initSkinLayout();
		initTitleButtonBar();
		initDataAndWindow();

	}

	private void initDataAndWindow() {

		EntryCatalogEntity catalogEntity = (EntryCatalogEntity) getIntent()
				.getSerializableExtra(
						HctConstants.ON_ACTIVITY_KEY_ENTRY_CATALOG_ENTITY);
		if (catalogEntity == null) {
			return;
		}
		Intent intent = getIntent();
		String sEntryTitleId = intent
				.getStringExtra(HctConstants.ON_ACTIVITY_KEY_ENTRY_TITLE_ID);

		String machineName = intent
				.getStringExtra(HctConstants.ON_ACTIVITY_KEY_SEARCH_MACHINE_NAME);
		String bookId = "";
		if (bUseCurrentId()) {
			bookId = intent
					.getStringExtra(HctConstants.ON_ACTIVITY_KEY_CURRENT_BOOK_ID);
		} else {
			bookId = intent
					.getStringExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ID);
		}
		int level = intent.getIntExtra("level", 1);
		EntryCatalogEntity.EntryLevel1Entity level1Entity = null;
		EntryCatalogEntity.EntryLevel1Entity.EntryLevel2Entity level2Entity = null;
		switch (level) {
		case 1:// 一级目录
			level1Entity = HctConstants.getLevel1Entity();
			HctConstants.level1Entity = null;
			break;
		case 2:// 2级目录
			level2Entity = HctConstants.getLevel2Entity();
			HctConstants.level2Entity = null;
			break;
		case 3:// 3级目录
			level2Entity = HctConstants.getLevel2Entity();
			HctConstants.level2Entity = null;
			break;
		default:
			break;
		}
		if (catalogEntity.dataList == null || catalogEntity.dataList.isEmpty()) {

		} else {
			for (int i = 0; i < catalogEntity.dataList.size(); i++) {
				EntryCatalogEntity.EntryLevel1Entity entity = catalogEntity.dataList
						.get(i);

				if (entity.dataList == null) {
					bookIds.put(entity.id, entity.bookId);
					titleNames.add(entity.titleContents);
					if (level == 1 && isEquals(level1Entity, entity)) {
						currentIndex = i;
					}
				} else {
					for (int j = 0; j < entity.dataList.size(); j++) {
						EntryCatalogEntity.EntryLevel1Entity.EntryLevel2Entity entity2 = entity.dataList
								.get(j);
						if (isEquals(level2Entity, entity2)) {
							bookIds.put(entity2.id, entity2.bookId);
							titleNames.add(entity2.titleContents);
							if (level == 2) {
								currentIndex = bookIds.size() - 1;
							} else if (level == 3) {
								for (int k = 0; k < entity2.dataList.size(); k++) {
									EntryCatalogEntity.EntryLevel1Entity.EntryLevel2Entity.EntryLevel3Entity entity3 = entity2.dataList
											.get(k);
									bookIds.put(entity3.id, entity3.bookId);
									titleNames.add(entity3.titleContents);
									if (bookId.equals(entity3.bookId)
											&& sEntryTitleId.equals(entity3.id)) {
										currentIndex = bookIds.size() - 1;
									}
								}
							}
						} else {
							bookIds.put(entity2.id, entity2.bookId);
							titleNames.add(entity2.titleContents);
						}
					}
				}
			}

		}
		initWindow(currentIndex, machineName);

	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (setHistoryViewGone()) {
				return true;
			}
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private boolean setHistoryViewGone() {
		final View historyView = findViewById(R.id.lyt_search_history);
		if (historyView.getVisibility() == View.VISIBLE) {
			historyView.setVisibility(View.GONE);
			clearFocus();
			return true;
		}
		return false;
	}

	private void initTitleButtonBar() {
		Intent intent = getIntent();
		String titleContents = intent
				.getStringExtra(HctConstants.ON_ACTIVITY_KEY_ENTRY_TITLE_CONTENTS);

		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(titleContents);

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private boolean bUseCurrentId() {
		Intent intent = getIntent();
		String bookId = intent
				.getStringExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ID);

		if (bookId.equals("")) {
			return true;
		} else {
			return false;
		}
	}

	private void initWindow(final int currentIndex, String machineName) {
		final Object[] keys = (Object[]) bookIds.keySet().toArray();
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(titleNames.get(currentIndex));

		final Button btnRight = (Button) findViewById(R.id.btn_right);
		btnRight.setBackgroundResource(R.drawable.btn_advice_selector);
		btnRight.setVisibility(View.VISIBLE);
		btnRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						SubmitAdviceActivity.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_ENTRY_TITLEID,
						keys[currentIndex].toString());
				startActivity(intent);
			}
		});

		initContentById(keys[currentIndex].toString(),
				bookIds.get(keys[currentIndex]), machineName);

		// Intent intent = getIntent();
		// // String filePath = intent
		// // .getStringExtra(HctConstants.ON_ZIP_SDCARD_PATH_KEY);
		// String sEntryTitleId = intent
		// .getStringExtra(HctConstants.ON_ACTIVITY_KEY_ENTRY_TITLE_ID);
		//
		// String machineName = intent
		// .getStringExtra(HctConstants.ON_ACTIVITY_KEY_SEARCH_MACHINE_NAME);
		// if (bUseCurrentId()) {
		// String bookId = intent
		// .getStringExtra(HctConstants.ON_ACTIVITY_KEY_CURRENT_BOOK_ID);
		// initContentById(sEntryTitleId, /* filePath, */bookId, machineName);
		// } else {
		// String bookId = intent
		// .getStringExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ID);
		// initContentById(sEntryTitleId, /* filePath, */bookId, machineName);
		// }

	}

	/**
	 * XXX
	 * 
	 * @param webView
	 * @param sHtmlContents
	 * @param sSearchInput
	 */
	private void initSearchCount(final WebView webView,
			final String sHtmlContents, final String sSearchInput) {

		final FrameLayout searchCountLyt = (FrameLayout) findViewById(R.id.lyt_search_count);
		final ProgressBar searchCountPb = (ProgressBar) findViewById(R.id.pb_search_count);
		if (sSearchInput.equals("")) {
			searchCountLyt.setVisibility(View.GONE);

			webView.loadDataWithBaseURL(null, sHtmlContents, "text/html",
					"uft-8", null);
			return;
		} else if (!sSearchInput.equals("")) {

			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					String sHighlightContents = (String) msg.obj;
					webView.loadDataWithBaseURL(null, sHighlightContents,
							"text/html", "uft-8", null);

					renderSearchCountTv(msg.what);
					searchCountPb.setVisibility(View.GONE);
				}
			};

			searchCountLyt.setVisibility(View.VISIBLE);
			searchCountPb.setVisibility(View.VISIBLE);
			new Thread() {
				public void run() {

					HightLightEntity entity = null;
					try {
						entity = setHighLightV2(sHtmlContents, sSearchInput);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (entity != null) {
						Message message = new Message();
						message.what = entity.iCount;
						message.obj = entity.sContents;
						handler.sendMessage(message);
					}

				}
			}.start();

		}

	}

	public static class HightLightEntity extends BaseEntity {
		private static final long serialVersionUID = -9042256048143460873L;
		public String sContents = "";
		public int iCount = 0;
	}

	// ================保护Html之外的内容=====================
	private HightLightEntity setHighLightV2(final String sHtmlContents,
			final String sSearchInput) {
		HightLightEntity lightEntity = new HightLightEntity();

		ArrayList<String> matches = new ArrayList<String>();
		String temp = protectContent(sHtmlContents, matches);
		int iCount = updateSearchCount(matches, sSearchInput);

		ArrayList<String> highLightMatches = setMachesHightLightBackground(
				matches, sSearchInput);

		String sHighlightContents = restoreHtml(temp, highLightMatches);

		lightEntity.sContents = sHighlightContents;
		lightEntity.iCount = iCount;
		return lightEntity;
	}

	private ArrayList<String> setMachesHightLightBackground(
			ArrayList<String> matches, String sSearchInput) {
		ArrayList<String> highLightMatches = new ArrayList<String>();
		for (String bean : matches) {
			String subBean = bean.substring(1, bean.length() - 1);
			String highLightMatche = setHightLightBackground(subBean,
					sSearchInput);
			highLightMatches.add(highLightMatche);
		}
		return highLightMatches;
	}

	private int updateSearchCount(ArrayList<String> matches,
			final String sSearchInput) {
		int iCount = 0;
		for (String bean : matches) {

			int start = 0;
			/**
			 * 截取掉“>开头”和“<结尾”
			 */
			String subBean = bean.substring(1, bean.length() - 1);
			while (subBean.indexOf(sSearchInput, start) >= 0
					&& start < subBean.length()) {
				iCount++;
				start = subBean.indexOf(sSearchInput, start)
						+ sSearchInput.length();
			}

		}
		return iCount;

	}

	private String protectContent(String input, ArrayList<String> matches) {
		Pattern htmlReg = Pattern.compile(">(.*?)<", Pattern.DOTALL
				| Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
		// 获取匹配集合
		Matcher matcher = htmlReg.matcher(input);
		while (matcher.find()) {

			String matche = matcher.group()/*
											 * .substring(1,
											 * matcher.group().length() - 1)
											 */;
			if (!matche.trim().equals("><")) {
				matches.add(matche);
			}

		}

		// 设置替换字串
		String markFormat = ">[[{%1$d}]]<";
		// 替换html,记录位置
		for (int i = 0; i < matches.size(); i++) {
			input = input.replaceFirst(Pattern.quote(matches.get(i)),
					String.format(markFormat, i));
		}
		return input;
	}

	// ================end of 保护Html之外的内容=====================

	// ================保护Html=====================
	private String setHightLightBackground(String sHtmlContents,
			String sSearchInput) {

		if (sHtmlContents.contains(sSearchInput)) {
			return sHtmlContents.replaceAll(Pattern.quote(sSearchInput),
					"<font style=color:white;background:orange>" + sSearchInput
							+ "</font>");
		} else {
			return sHtmlContents;
		}

	}

	/**
	 * 将标号恢复html(恢复html标签)
	 * 
	 * @param input
	 * @param matches
	 * @return
	 */
	private String restoreHtml(String input, ArrayList<String> matches) {
		// 设置替换字串
		String markFormat = "[[{%1$d}]]";
		for (int i = 0; i < matches.size(); i++) {
			input = input
					.replaceFirst(Pattern.quote(String.format(markFormat, i)),
							matches.get(i));
		}
		return input;
	}

	// ==================end of 保护Html===================
	private void initSearchHistroyLv(final EditText searchInputEt,
			final WebView webView, final String sHtmlContents) {
		final LinearLayout searchHistoryLyt = (LinearLayout) findViewById(R.id.lyt_search_history);
		ListView searchHistoryLv = (ListView) findViewById(R.id.lst_default_list_search);

		HctApplication application = (HctApplication) getApplication();
		DbKeywordController dbKeywordController = new DbKeywordController(
				application.getDbKeywordAdapter());

		final KeywordListEntity listEntity = dbKeywordController
				.getKeywordListEntity();
		if (listEntity.dataList != null && listEntity.dataList.size() > 0) {

			searchHistoryLyt.setVisibility(View.VISIBLE);
		} else if (listEntity.dataList == null) {
			searchHistoryLyt.setVisibility(View.GONE);
			return;
		}
		new SearchHistoryListAdapter(EntryDetailV3Activity.this,
				searchHistoryLv, listEntity.dataList, 0);
		searchHistoryLv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				KeywordEntity entity = listEntity.dataList.get(position);
				searchInputEt.setText(entity.keyword);
				setHistoryViewGone();
				initSearchCount(webView, sHtmlContents, searchInputEt
						.getEditableText().toString().trim());
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(EntryDetailV3Activity.this);
				clearFocus();
			}

		});
	}

	private void clearFocus() {

		/**
		 * 使用EditText左侧的ImageView抢Focus
		 */
		ImageView searchIconIv = (ImageView) findViewById(R.id.iv_search_icon);
		searchIconIv.requestFocus();

		final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
		searchInputEt.clearFocus();
	}

	private void initSearchBar(final WebView webView, final String sHtmlContents) {

		final EditText searchInputEt = (EditText) findViewById(R.id.et_search_input);
		final ImageButton clearBtn = (ImageButton) findViewById(R.id.btn_clear);

		searchInputEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				String sInput = searchInputEt.getText().toString().trim();
				if (sInput.equals("")) {
					clearBtn.setVisibility(View.GONE);
				} else if (!sInput.equals("")) {
					clearBtn.setVisibility(View.VISIBLE);
				}
			}

		});
		searchInputEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					setHistoryViewGone();
				} else if (hasFocus) {
					initSearchHistroyLv(searchInputEt, webView, sHtmlContents);
				}

			}
		});

		searchInputEt.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH
						|| keyCode == KeyEvent.KEYCODE_UNKNOWN
						|| keyCode == KeyEvent.KEYCODE_ENTER) {
					setHistoryViewGone();
					initSearchCount(webView, sHtmlContents, searchInputEt
							.getEditableText().toString().trim());

					insert2Db(searchInputEt);

					KeyboardUtil keyboardUtil = new KeyboardUtil();
					keyboardUtil.hideSoftKeyboard(v);
					clearFocus();
					return true;
				}
				return false;
			}

			private void insert2Db(final EditText searchInputEt) {
				String sInput = searchInputEt.getEditableText().toString()
						.trim();
				if (sInput.equals("")) {
					return;
				}
				HctApplication application = (HctApplication) getApplication();
				DbKeywordController dbKeywordController = new DbKeywordController(
						application.getDbKeywordAdapter());

				KeywordEntity entity = new KeywordEntity();
				entity.keyword = sInput;
				dbKeywordController.insert(entity);
			}

		});

		clearBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				searchInputEt.setText("");
				setHistoryViewGone();
				initSearchCount(webView, sHtmlContents, searchInputEt
						.getEditableText().toString().trim());

				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				clearFocus();
			}
		});

	}

	private void renderSearchCountTv(int iCount) {
		final TextView searchCountTv = (TextView) findViewById(R.id.tv_search_count);

		String sCount = getString(R.string.search_count_hint);
		sCount = String.format(sCount, iCount);
		searchCountTv.setText(sCount);
	}

	private String dealTable(String contents, String machineName) {

		if (!contents.contains("<span >****####</span>")) {
			return contents;
		}
		if (contents.contains("<span >****####</span>")
				&& machineName.equals("")) {
			return contents.replaceAll(Pattern.quote("<span >****####</span>"),
					"");
		}
		String[] aContents = contents.split(Pattern
				.quote("<span >****####</span>"));
		String tmpContents = "";
		for (int i = 0; i < aContents.length; i++) {
			if (i % 2 != 1) {
				tmpContents += aContents[i];
			}
			/**
			 * 奇数为两个<span >****####</span>之间的内容
			 */
			if (i % 2 == 1) {
				if (aContents[i].contains("</table>")) {
					String[] tableContents = aContents[i].split("</table>");

					String tmpTableContents = "";
					for (int j = 0; j < tableContents.length; j++) {
						if (tableContents[j].contains("</td>")) {
							String[] tdContents = tableContents[j]
									.split("</td>");
							if (tdContents.length > 0) {
								if (tdContents[0].contains(machineName)) {
									tmpTableContents += tableContents[j]
											+ "</table>";
								}
							}
						}
					}
					tmpContents += tmpTableContents;
				}

			}
		}

		return tmpContents;
	}

	private void initContentById(final String id, /* final String filePath, */
			final String bookId, final String machineName) {
		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
		final LinearLayout reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_reload);
		final Button reloadBtn = (Button) findViewById(R.id.btn_default_reload);
		final PullToRefreshWebView pullRefreshWebView = (PullToRefreshWebView) findViewById(R.id.wv_contents);
		final WebView webView = pullRefreshWebView.getRefreshableView();
		pullRefreshWebView
				.setOnRefreshListener(new OnRefreshListener<WebView>() {

					@Override
					public void onRefresh(PullToRefreshBase<WebView> refreshView) {
						if (refreshView.getCurrentMode() == Mode.PULL_FROM_START) {
							if (currentIndex > 0) {
								currentIndex--;
								initWindow(currentIndex, machineName);
							} else {
								pullRefreshWebView.onRefreshComplete();
							}

						} else if (refreshView.getCurrentMode() == Mode.PULL_FROM_END) {
							if (currentIndex < bookIds.size() - 1) {
								currentIndex++;
								initWindow(currentIndex, machineName);
							} else {
								pullRefreshWebView.onRefreshComplete();
							}
						}
					}

				});

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:

					hctResult = (HctResult) msg.obj;

					EntryEntity entity = (EntryEntity) hctResult.data;

					// renderEntryContents(entity);
					if (!entity.contents.equals("")) {

						renderEntryContentsUseWebView(entity);
					} else if (entity.contents.equals("")) {
						initMultiContentById(id, /* filePath, */bookId,
								machineName);
					}
					pullRefreshWebView.onRefreshComplete();
					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							initContentById(id, /* filePath, */bookId,
									machineName);
						}
					});
					pullRefreshWebView.onRefreshComplete();
					break;
				}
			}

			private WebViewClient mWebViewClient = new WebViewClient() {
				@Override
				public void onReceivedError(WebView view, int errorCode,
						String description, String failingUrl) {
					super.onReceivedError(view, errorCode, description,
							failingUrl);
				}

				@Override
				public void onReceivedHttpAuthRequest(WebView view,
						HttpAuthHandler handler, String host, String realm) {
					super.onReceivedHttpAuthRequest(view, handler, host, realm);
				}

				@Override
				public void onLoadResource(WebView view, String url) {
					super.onLoadResource(view, url);
				}

				@Override
				public void onPageFinished(WebView view, String url) {
					super.onPageFinished(view, url);
					addImageClickListner(webView);
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);
				}

				@Override
				public void onPageStarted(WebView view, String url,
						Bitmap favicon) {
					super.onPageStarted(view, url, favicon);
				}

				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					// if (view != null) {
					// view.loadUrl(url);
					// }
					Intent intent = new Intent();
					intent.setAction("android.intent.action.VIEW");
					Uri content_url = Uri.parse(url);
					intent.setData(content_url);
					startActivity(intent);
					return true;
				}
			};

			@SuppressLint("JavascriptInterface")
			private void renderEntryContentsUseWebView(final EntryEntity entity) {

				// 取消滚动条
				webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
				webView.setWebViewClient(mWebViewClient);

				webView.requestFocus(View.FOCUS_DOWN);
				webView.getSettings().setBlockNetworkImage(false);
				webView.getSettings().setSupportZoom(true);
				webView.getSettings().setDefaultTextEncodingName("UTF-8");
				webView.getSettings().setBuiltInZoomControls(true);

				webView.getSettings().setJavaScriptEnabled(true);
				webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(
						true);
				webView.getSettings()
						.setPluginState(WebSettings.PluginState.ON);
				webView.getSettings().setSupportMultipleWindows(true);
				webView.getSettings().setTextSize(TextSize.NORMAL);

				webView.getSettings().setSaveFormData(false);
				webView.getSettings().setSavePassword(false);
				webView.getSettings().setUseWideViewPort(false);
				webView.setSaveEnabled(false);
				webView.clearCache(true);

				modifySrcTag(entity);
				webView.addJavascriptInterface(new JavascriptInterface(
						EntryDetailV3Activity.this), "imagelistner");
				webView.loadDataWithBaseURL(null, entity.contents, "text/html",
						"uft-8", null);

				initSearchBar(webView, entity.contents);

			}

			/**
			 * 修改Src标签
			 * 
			 * @param entryEntity
			 */
			private void modifySrcTag(EntryEntity entryEntity) {
				DbController dbController = new DbController(
						EntryDetailV3Activity.this);
				BookEntity bookEntity;
				if (bUseCurrentId()) {
					bookEntity = dbController
							.getBookEntityUseCurrentId(entryEntity.bookId);
				} else {
					bookEntity = dbController.getBookEntity(entryEntity.bookId);
				}
				String filePath = BookEntity.makeBookFileName(
						bookEntity.download_url, bookEntity.suffix,
						getApplicationContext());
				/**
				 * 解压后的文件路径,形如“//mnt/sdcard/”
				 */
				String dePath = UnZipUtil.getDeCompressionFilePath(filePath);
				String sContents = entryEntity.contents.replace("BOOKID=",
						"file://" + dePath + "/").replace("&ID=", "/");
				sContents = dealTable(sContents, machineName);
				entryEntity.contents = sContents;
			}
		};

		webView.setBackgroundColor(0); // 设置背景色
		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							EntryDetailV3Activity.this);

					HctResult result = controller.getEntryContent(bookId, id);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void initMultiContentById(final String id, /*
														 * final String
														 * filePath,
														 */
			final String bookId, final String machineName) {
		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
		final LinearLayout reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_reload);
		final Button reloadBtn = (Button) findViewById(R.id.btn_default_reload);

		final PullToRefreshWebView pullToRefreshWebView = (PullToRefreshWebView) findViewById(R.id.wv_contents);
		final WebView webView = pullToRefreshWebView.getRefreshableView();
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:

					hctResult = (HctResult) msg.obj;

					BookZipTxtEntity entity = (BookZipTxtEntity) hctResult.data;

					// renderMultiEntryContents(entity);
					renderMultiEntryContentsUseWebView(entity);
					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							initMultiContentById(id, /* filePath, */bookId,
									machineName);
						}
					});
					break;
				}
			}

			private WebViewClient mWebViewClient = new WebViewClient() {
				@Override
				public void onReceivedError(WebView view, int errorCode,
						String description, String failingUrl) {
					super.onReceivedError(view, errorCode, description,
							failingUrl);
				}

				@Override
				public void onReceivedHttpAuthRequest(WebView view,
						HttpAuthHandler handler, String host, String realm) {
					super.onReceivedHttpAuthRequest(view, handler, host, realm);
				}

				@Override
				public void onLoadResource(WebView view, String url) {
					super.onLoadResource(view, url);
				}

				@Override
				public void onPageFinished(WebView view, String url) {
					super.onPageFinished(view, url);
					addImageClickListner(webView);
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);
				}

				@Override
				public void onPageStarted(WebView view, String url,
						Bitmap favicon) {
					super.onPageStarted(view, url, favicon);
				}

				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					// if (view != null) {
					// view.loadUrl(url);
					// }
					Intent intent = new Intent();
					intent.setAction("android.intent.action.VIEW");
					Uri content_url = Uri.parse(url);
					intent.setData(content_url);
					startActivity(intent);
					return true;
				}
			};

			@SuppressLint("JavascriptInterface")
			private void renderMultiEntryContentsUseWebView(
					final BookZipTxtEntity bean) {
				if (bean.entryList == null) {
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);
					return;
				}

				for (EntryEntity entryEntity : bean.entryList) {
					modifySrcTag(entryEntity);
				}

				String sMultiContents = "";
				for (EntryEntity entryEntity : bean.entryList) {
					String sTitle = "<p align=left style=font-size:14pt;font-weight:bold;color:black>"
							+ entryEntity.titleContents + "</p>";
					sMultiContents += sTitle + entryEntity.contents;
				}

				// 取消滚动条
				webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
				webView.setWebViewClient(mWebViewClient);

				webView.requestFocus(View.FOCUS_DOWN);
				webView.getSettings().setBlockNetworkImage(false);
				webView.getSettings().setSupportZoom(true);
				webView.getSettings().setDefaultTextEncodingName("UTF-8");
				webView.getSettings().setBuiltInZoomControls(true);

				webView.getSettings().setJavaScriptEnabled(true);
				webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(
						true);
				// webView.getSettings().setPluginState(true);
				webView.getSettings()
						.setPluginState(WebSettings.PluginState.ON);
				webView.getSettings().setSupportMultipleWindows(true);
				webView.getSettings().setTextSize(TextSize.NORMAL);

				webView.getSettings().setSaveFormData(false);
				webView.getSettings().setSavePassword(false);
				webView.getSettings().setUseWideViewPort(false);
				webView.setSaveEnabled(false);
				webView.clearCache(true);

				webView.addJavascriptInterface(new JavascriptInterface(
						EntryDetailV3Activity.this), "imagelistner");

				webView.loadDataWithBaseURL(null, sMultiContents, "text/html",
						"uft-8", null);
				initSearchBar(webView, sMultiContents);
			}

			/**
			 * 修改Src标签
			 * 
			 * @param entryEntity
			 */
			private void modifySrcTag(EntryEntity entryEntity) {
				DbController dbController = new DbController(
						EntryDetailV3Activity.this);
				BookEntity bookEntity;
				if (bUseCurrentId()) {
					bookEntity = dbController
							.getBookEntityUseCurrentId(entryEntity.bookId);
				} else {
					bookEntity = dbController.getBookEntity(entryEntity.bookId);
				}

				String filePath = BookEntity.makeBookFileName(
						bookEntity.download_url, bookEntity.suffix,
						getApplicationContext());
				/**
				 * 解压后的文件路径,形如“//mnt/sdcard/”
				 */
				String dePath = UnZipUtil.getDeCompressionFilePath(filePath);
				String sContents = entryEntity.contents.replace("BOOKID=",
						"file://" + dePath + "/").replace("&ID=", "/");
				sContents = dealTable(sContents, machineName);
				entryEntity.contents = sContents;
			}

		};

		webView.setBackgroundColor(0); // 设置背景色
		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							EntryDetailV3Activity.this);

					HctResult result = controller.getMultiEntryContentLst(
							bookId, id);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private class TouchListenerImpl implements OnTouchListener {
		private WebView webView;

		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = view.getScrollY();
				int height = view.getHeight();
				int scrollViewMeasuredHeight = webView.getChildAt(0)
						.getMeasuredHeight();
				if (scrollY == 0) {
					System.out.println("滑动到了顶端 view.getScrollY()=" + scrollY);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {
					System.out.println("滑动到了底部 scrollY=" + scrollY);
					System.out.println("滑动到了底部 height=" + height);
					System.out.println("滑动到了底部 scrollViewMeasuredHeight="
							+ scrollViewMeasuredHeight);
				}
				break;

			default:
				break;
			}
			return false;
		}

	};

	// 注入js函数监听
	private void addImageClickListner(WebView webView) {
		// 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，在还是执行的时候调用本地接口传递url过去
		webView.loadUrl("javascript:(function(){"
				+ "var objs = document.getElementsByTagName(\"img\"); "
				+ "for(var i=0;i<objs.length;i++)  " + "{"
				+ "    objs[i].onclick=function()  " + "    {  "
				+ "        window.imagelistner.openImage(this.src);  "
				+ "    }  " + "}" + "})()");
	}

	// js通信接口
	public class JavascriptInterface {

		private Context context;

		public JavascriptInterface(Context context) {
			this.context = context;
		}

		public void openImage(String img) {
			Intent intent = new Intent();
			intent.putExtra("image", img);
			intent.setClass(EntryDetailV3Activity.this,
					ShowMegaImageActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}

	private boolean isEquals(EntryCatalogEntity.EntryLevel1Entity l,
			EntryCatalogEntity.EntryLevel1Entity r) {
		if (l == null || r == null) {
			return false;
		}

		return l.id.equals(r.id) && l.bookId.equals(r.bookId);
	}

	private boolean isEquals(
			EntryCatalogEntity.EntryLevel1Entity.EntryLevel2Entity l,
			EntryCatalogEntity.EntryLevel1Entity.EntryLevel2Entity r) {
		if (l == null || r == null) {
			return false;
		}

		return l.id.equals(r.id) && l.bookId.equals(r.bookId);
	}
}
